/**************************************************************************
** CuteRSS is a simple RSS/Atom client for managing RSS/Atom Feeds
**
** Copyright (C) 2010 Prakash Nadar <prakash.nadar@gmail.com>
**
** This program is free software: you can redistribute it and/or modify
**     it under the terms of the GNU General Public License as published by
**     the Free Software Foundation, either version 3 of the License, or
**     (at your option) any later version.
**
**     This program is distributed in the hope that it will be useful,
**     but WITHOUT ANY WARRANTY; without even the implied warranty of
**     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**     GNU General Public License for more details.
**
**     You should have received a copy of the GNU General Public License
**     along with this program.  If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "rssfeeddatamodel.h"
#include "rssdata.h"
#include "newfeeddialog.h"
#include <QDesktopServices>
#include <QDomDocument>
#include <QFile>
#include <QSystemTrayIcon>

#include <qdebug.h>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->webView->page()->setLinkDelegationPolicy(QWebPage::DelegateExternalLinks);
    initTreeWidget();
    initSysTrayIcon();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initSysTrayIcon()
{
    QSystemTrayIcon* trayIcon = new QSystemTrayIcon(this);
    trayIcon->setIcon(QIcon(":/images/rss.png"));
    trayIcon->show();
    connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
}


void MainWindow::initTreeWidget()
{
    QTreeWidgetItem * item = new QTreeWidgetItem(ui->treeWidget);
    item->setExpanded(true);

    item->setText(0,"All Feeds");
    ui->treeWidget->addTopLevelItem(item);

    QDomDocument xmlDoc("FeedInfo.xml");
    QFile xmlFile("feedinfo.xml");
    if(!xmlFile.open(QIODevice::ReadOnly)){
        return;
    }
    if (!xmlDoc.setContent(&xmlFile)) {
        xmlFile.close();
        return;
    }
    QDomElement docElem = xmlDoc.documentElement(); 
    xmlFile.close();

    processNode(docElem,item);
}

void MainWindow::processNode(QDomElement parent, QTreeWidgetItem *parentItem)
{
    QDomNodeList feedList = parent.childNodes();
    for(int index = 0; index < feedList.count(); index++) {
        QTreeWidgetItem * item;
        TreeItemData* itemData;
        if(feedList.at(index).toElement().nodeName() == "feed") {
            QString feedUrl = feedList.at(index).attributes().namedItem("url").nodeValue();
            QString feedName = feedList.at(index).attributes().namedItem("name").nodeValue();

            itemData = new TreeItemData;
            item = new QTreeWidgetItem(parentItem);
            item->setText(0,feedName);
            itemData->setUrl(feedUrl);
            item->setData(0, Qt::UserRole, QVariant::fromValue<TreeItemData*>(itemData));
        } else if(feedList.at(index).toElement().nodeName() == "folder") {
            QString folderName = feedList.at(index).attributes().namedItem("name").nodeValue();
            item = new QTreeWidgetItem(parentItem);
            item->setExpanded(true);
            item->setText(0,folderName);
            processNode(feedList.at(index).toElement(), item);
        }
    }
}

void MainWindow::treeItemClicked ( QTreeWidgetItem * item, int column )
{
    //TODO: move the model initialisation code to the TreeItemData.
    TreeItemData* itemData;
    itemData = item->data(0, Qt::UserRole).value<TreeItemData *>();
    if(itemData) {
        ui->rssItemView->setModel(itemData->model());
    }
}

void MainWindow::rssItemClicked(QModelIndex index)
{
    RssItemData* item = index.data(Qt::UserRole).value<RssItemData*>();
    QString htmlHeader = "<a href='"+ item->mLink +"'>" + item->mTitle + "</a><hr>" + item->mDescription;

    ui->webView->setHtml(htmlHeader);

    item->mRead = true;
    ui->rssItemView->model()->setData(index,QVariant(),Qt::UserRole);
}

void MainWindow::rssItemDblClicked(QModelIndex index)
{
    rssItemClicked(index);
    RssItemData* item = index.data(Qt::UserRole).value<RssItemData*>();
    QDesktopServices::openUrl(item->mLink);
}


void MainWindow::on_actionQuit_triggered()
{

}

void MainWindow::actionReload(bool checked)
{
    qDebug() << "Reload";
}

void MainWindow::actionAddNew(bool checked)
{
    NewFeedDialog dialog(this);
    dialog.exec();
}

void MainWindow::webViewLinkClicked(QUrl url)
{
    QString share;
    share = "http://www.facebook.com/sharer.php?u=www.hotmail.com&t=hotmail";

    //QDesktopServices::openUrl(share);
    QDesktopServices::openUrl(url);
}

void MainWindow::trayIconActivated (QSystemTrayIcon::ActivationReason reason )
{
    qDebug() << "I was clicked :" << reason;
}
